package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 菜品添加
     * @return
     */
    @Transactional//开始声明式事务
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.save(dish);
        List<DishFlavor> flavorList = null;
        if (dishDTO.getFlavors()!=null){
            flavorList = dishDTO.getFlavors().stream().map(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
                return dishFlavor;
            }).collect(Collectors.toList());
        }

        dishFlavorMapper.saveDishFlavor(flavorList);
    }
    /**
     * 菜品分页查询
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.page(pageQueryDTO);
        List<DishVO> list = page.getResult().stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            Category byId = categoryMapper.findById(dish.getCategoryId());
            dishVO.setCategoryName(byId.getName());
            return dishVO;
        }).collect(Collectors.toList());
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Transactional
    @Override
    public void delByIds(List<Long> ids) {
        ids = ids.stream().map(id->dishMapper.serviceByIds(id)).collect(Collectors.toList());
        List<Long> newIds = new ArrayList<>();
        for (Long id : ids) {
            if (id!=null) {
                newIds.add(id);
            }
        }
        if (newIds.size()==0 ) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        /* newIds = ids.stream().map(id -> setmealDishMapper.serviceByIds(id)==null ? setmealDishMapper.serviceByIds(id):1).collect(Collectors.toList());
         newIds = new ArrayList<>();
        for (Long id : newIds) {
            if (id==null) {
                newIds.add(id);
            }
        }
        if (newIds.size()==0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }*/
        dishMapper.delByIds(newIds);
        dishFlavorMapper.delByDishIds(newIds);

        Set keys = redisTemplate.keys("DISH_*");
        redisTemplate.delete(keys);
    }
    @Transactional
    @Override
    public void upDate(Dish dish) {

        //当菜品修改为停售时，套餐也改为停售
        if (dish.getStatus().equals(0)) {

            //通过中间表得到setmealDish; 用setmealDish.setmealId修改setmeal的状态
            List<SetmealDish> setmealDishes = setmealDishMapper.dishById(dish);
            for (SetmealDish setmealDish : setmealDishes) {
                setmealMapper.upStatus(setmealDish.getSetmealId(),dish.getStatus());
            }
        }
        dishMapper.upDate(dish);
        //清理缓存
        Set keys = redisTemplate.keys("DISH_*");
        redisTemplate.delete(keys);
    }

    @Override
    public DishVO dishById(Long id) {
        Dish dish = dishMapper.dishById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        return dishVO;
    }

    @Override
    public List<Dish> list(Long categoryId) {

        return dishMapper.list(categoryId);
    }

    /**
     * 条件查询菜品和口味
     * @return
     */
    public List<DishVO> listWithFlavor(DishDTO dishDTO) {
        String CACHE_KEY = "DISH_"+dishDTO.getCategoryId();
        //1.查缓存
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(CACHE_KEY);
        //2.判断
        if(dishVOList != null){
            return dishVOList;
        }


        List<Dish> dishList = dishMapper.findDishesByCid(dishDTO);

        dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.findByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}